<template> 
	<div class="padding20">
		<div class="margin-bottom20">系统用户</div>
		<el-form :inline="true" :model="listQuery" size="small" label-width="80">
			<el-form-item label="用户名：">
				<el-input v-model="listQuery.name" class="input-width" placeholder="用户名"></el-input>
			</el-form-item>
			<el-form-item label="角色：">
				<el-select v-model="listQuery.roleId" clearable>
					<el-option v-for="(item,index) in roleData" :key="index" :label="item.name" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button style="float:right" type="primary" @click="handleSearchList()" size="small">
					搜索
				</el-button>
				<el-button style="float:right;margin-right: 15px" @click="handleResetSearch()" size="small">
					重置
				</el-button>
			</el-form-item>
		</el-form>
		<div class="row-me row-center space-between">
			<div class="batch-operate-container">
				<el-select size="small" v-model="operateType" placeholder="批量操作">
					<el-option v-for="item in operateOptions" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
				<el-button style="margin-left: 20px" class="search-button" @click="handleBatchOperate()" type="primary"
					size="small">
					确定
				</el-button>
			</div>
			<el-button class="btn-add row-me center-all" style="height: 30px;" @click="handleAddAdminUser(0,{})"
				type="primary">
				添加
			</el-button>
		</div>
		<div class="table-container">
			<el-table ref="orderTable" :data="list" style="width: 100%;" @selection-change="handleSelectionChange"
				v-loading="listLoading" border>
				<el-table-column type="selection" width="40" align="center"></el-table-column>
				<el-table-column label="序号" type="index" width="70" align="center"></el-table-column>
				<el-table-column label="用户名" align="center">
					<template slot-scope="scope">{{ scope.row.name }}</template>
				</el-table-column>
				<el-table-column label="用户名" align="center">
					<template slot-scope="scope">{{ scope.row.loginName }}</template>
				</el-table-column>
				<el-table-column label="角色" align="center">
					<template slot-scope="scope">
						<el-tag v-for="role in scope.row.roles" :key="'has_' + role.id"
							style="margin-right: 10px;margin-bottom: 8px;">
							{{ role.name }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="科目" align="center" prop="remark"></el-table-column>
				<el-table-column label="操作" width="300" align="center">
					<template slot-scope="scope">
						<el-button size="mini" @click="handleAddAdminUser(scope.$index, scope.row)">编辑
						</el-button>
						<el-button size="mini" type="danger" @click="handleDeleteAdminUser(scope.$index, scope.row)">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div class="pagination-container">
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total, sizes,prev, pager, next,jumper" :current-page.sync="listQuery.pageNumber"
				:page-size="listQuery.pageSize" :page-sizes="[5, 10, 15]" :total="total">
			</el-pagination>
		</div>
		<!-- 新增编辑用户 -->
		<el-dialog :title="title" :visible.sync="visible" width="30%">
			<el-form :model="adminUser" :rules="rules" ref="adminUserFrom" label-width="100px">
				<el-form-item label="用户名：" prop="name">
					<el-input v-model="adminUser.name"></el-input>
				</el-form-item>
				<el-form-item label="账号：" prop="loginName">
					<el-input v-model="adminUser.loginName"></el-input>
				</el-form-item>
				<el-form-item v-if="!isEdit" label="密码：" prop="password">
					<el-input v-model="adminUser.password"></el-input>
				</el-form-item>
				<el-form-item label="角色：" prop="roleIds">
					<el-select v-model="adminUser.roleIds" clearable class="width100Per">
						<el-option v-for="(item,index) in roleData" :key="index" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="科目">
					<el-select v-model="adminUser.appids" clearable class="width100Per" filterable multiple>
						<el-option v-for="(item,index) in miniApps" :key="index" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="visible=false">取 消</el-button>
					<el-button type="primary" @click="onSubmit('adminUserFrom')">保 存</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 编辑用户角色 -->
		<el-dialog title="角色编辑" :visible.sync="editRoleVisible" width="40%" @close="getList">
			<template>
				<el-select filterable v-model="editRole.roleIds" class="mr20" multiple placeholder="请选择角色">
					<el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id">
					</el-option>
				</el-select>
				<el-button type="primary" @click="submitUserRole">更 新</el-button>
				<el-divider></el-divider>
			</template>
		</el-dialog>
	</div>
</template>

<script>
	import {
		fetchList,
		deleteAdminUser,
		updateAdminUser,
		updateUserRole
	} from '@/api/adminUser'
	import {
		fetchAllRole
	} from '@/api/role'
	import {
		formatDate
	} from '@/utils/date';
	import {
		treeselect
	} from "@/api/dept";
	import Treeselect from "@riophae/vue-treeselect";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";

	const defaultListQuery = {
		pageNumber: 1,
		pageSize: 10,
		name: null,
		mobile: null,
	};
	export default {
		name: "adminUserList",
		components: {
			Treeselect
		},
		data() {
			return {
				listQuery: Object.assign({}, defaultListQuery),
				listLoading: true,
				list: null,
				total: null,
				operateType: null,
				editRoleVisible: false,
				visible: false,
				multipleSelection: [],
				roles: [],
				editRole: {
					'userId': '',
					'roleIds': []

				},
				defaultProps: {
					children: "children",
					label: "label"
				},
				statusOptions: [{
						label: '正常',
						value: 0
					},
					{
						label: '暂停',
						value: 1
					}
				],
				operateOptions: [{
					label: "批量删除",
					value: 3
				}],
				rules: {
					name: [{
						required: true,
						message: '请输入用户名',
						trigger: 'blur'
					}],
					loginName: [{
						required: true,
						message: '请输入账号',
						trigger: 'blur'
					}],
					headImage: [{
						required: true,
						message: '请上传头像',
						trigger: 'blur'
					}],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					}],
					roleIds: [{
						required: true,
						message: '请选择角色',
						trigger: 'change'
					}],
					isLocked: [{
						required: true,
						message: '请选择状态',
						trigger: 'change'
					}],
				},
				title: '',
				// 部门名称
				name: undefined,
				// 部门树选项
				deptOptions: undefined,
				logisticsDialogVisible: false,
				roleData: [],
				adminUser: {
					roleIds: ''
				},
				isEdit: false,
				miniApps: []
			}
		},
		watch: {
			// 根据名称筛选部门树
			name(val) {
				this.$refs.tree.filter(val);
			}
		},
		created() {
			this.getList();
			this.getTreeselect();
			this.getRoleList();
			this.getRoleData()
			this.getMiniApp()
		},
		filters: {
			formatCreateTime(time) {
				let date = new Date(time);
				return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
			},
			formatStatus(value) {
				if (value === 0) {
					return '正常';
				} else if (value === 1) {
					return '暂停';
				}
			},
		},
		methods: {
			getMiniApp() {
				this.$get('/admin/minis/getAll').then(res => {
					this.miniApps = res.data;
				})
			},
			onSubmit() {
				this.$refs['adminUserFrom'].validate(async (valid) => {
					if (valid) {
						if (!Array.isArray(this.adminUser.roleIds)) {
							this.adminUser.roleIds = [this.adminUser.roleIds] || []
						}
						let appids = []
						let appidName = this.adminUser.appidName || []
						if (this.adminUser.appids && this.adminUser.appids.length != 0) {
							appids = this.adminUser.appids
							if (!appidName || appidName.length == 0) {
								for (let val of appids) {
									for (let item of this.miniApps) {
										if (val == item.id) {
											appidName.push(item.name)
										}
									}
								}
							}
						} else {
							appids = Array.from(this.miniApps, ({
								id
							}) => id).flat(1)
							appidName = Array.from(this.miniApps, ({
								name
							}) => name).flat(1)
						}
						const res = await this.$post('/admin/adminUser/saveAdminUser', {
							...this.adminUser,
							appids: appids.toString(),
							position: appids.toString(),
							remark: appidName.toString()
						})
						if (res.code == 1000) {
							this.$message.success('操作成功')
							this.getList()
							this.visible = false
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				})
			},
			async getRoleData() {
				const res = await this.$get('/admin/role/getAll')
				this.roleData = res.data
			},
			// 筛选节点
			filterNode(value, data) {
				if (!value) return true;
				return data.label.indexOf(value) !== -1;
			},
			// 节点单击事件
			handleNodeClick(data) {
				this.listQuery.departmentId = data.id;
				this.getList();
			},
			/** 查询部门下拉树结构 */
			getTreeselect() {
				treeselect().then(response => {
					this.deptOptions = response.data;
				});
			},
			handleLockChange(index, row) {
				this.lockAdminUser(index, row);
			},
			handleUpdateAdminUser(index, row) {
				this.$router.push({
					path: '/adminUser/update',
					query: {
						id: row.id
					}
				})
			},
			handleUpdateRole(index, row) {
				this.editRoleVisible = true;
				this.editRole.userId = row.id;
				this.editRole.roleIds = [];
				for (let i = 0; i < row.roles.length; i++) {
					this.editRole.roleIds.push(row.roles[i].id);
				}
			},
			handleAddAdminUser(index, row) {
				if (row.id) {
					this.title = '修改系统用户'
					this.adminUser = row
					this.$set(this.adminUser, 'roleIds', row.roleIds)
					this.isEdit = true
					if (this.adminUser.roles && this.adminUser.roles.length != 0) {
						this.adminUser.roleIds = this.adminUser.roles[0].id
					}
					if (this.adminUser.tails && this.adminUser.tails.appids) {
						this.adminUser.appids = this.adminUser.appids.split(',')
					}
					if (this.adminUser.tails && this.adminUser.tails.appidName) {
						this.adminUser.appidName = this.adminUser.appidName.split(',')
					}
				} else {
					this.title = '新增系统用户'
					this.adminUser = {}
					this.isEdit = false
				}
				this.visible = true
			},
			handleResetSearch() {
				this.listQuery = Object.assign({}, defaultListQuery);
				this.handleSearchList()
			},
			handleSearchList() {
				this.listQuery.pageNumber = 1;
				this.getList();
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			handleDeleteAdminUser(index, row) {
				let ids = [];
				ids.push(row.id);
				this.deleteAdminUser(ids);
			},
			handleBatchOperate() {
				if (this.multipleSelection == null || this.multipleSelection.length < 1) {
					this.$message({
						message: '请选择要操作的数据',
						type: 'warning',
						duration: 1000
					});
					return;
				}
				if (this.operateType === 3) {
					//批量删除
					let ids = [];
					for (let i = 0; i < this.multipleSelection.length; i++) {
						ids.push(this.multipleSelection[i].id);
					}
					this.deleteAdminUser(ids);
				}
			},
			handleSizeChange(val) {
				this.listQuery.pageNumber = 1;
				this.listQuery.pageSize = val;
				this.getList();
			},
			handleCurrentChange(val) {
				this.listQuery.pageNumber = val;
				this.getList();
			},
			getList() {
				this.listLoading = true;
				fetchList(this.listQuery).then(response => {
					this.listLoading = false;
					this.list = response.data.list;
					this.total = response.data.totalRow;
				});
			},
			getRoleList() {
				fetchAllRole().then(response => {
					this.roles = response.data;
				});
			},
			deleteAdminUser(ids) {
				this.$confirm('确定删除该用户吗，删除后将不可恢复', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteAdminUser(ids).then(response => {
						this.$message({
							message: '删除成功！',
							type: 'success',
							duration: 1000
						});
						this.getList();
					});
				}, () => {})
			},
			submitUserRole() {
				this.$confirm('更新角色会清空已有角色，是否更新?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					updateUserRole(this.editRole).then(response => {
						this.$message({
							message: '操作成功！',
							type: 'success',
							duration: 1000
						});
						this.getList();
						this.editRoleVisible = false;
					});
				}, () => {})
			},
			lockAdminUser(index, row) {
				if (row.id == 1) {
					this.$message({
						message: '超级管理员是神圣不可侵犯的！',
						type: 'error',
						duration: 1000
					});
					row.isLocked = !row.isLocked;
					return;
				}
				let user = {
					id: row.id,
					isLocked: row.isLocked
				}
				this.$confirm('是否要进行该操作?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					updateAdminUser(user).then(response => {
						this.$message({
							message: '操作成功！',
							type: 'success',
							duration: 1000
						});
						this.getList();
					});
				}, () => {
					row.isLocked = !row.isLocked;
				})
			}
		}
	}
</script>
<style scoped>
	.input-width {
		width: 203px;
	}
</style>